package com.cake.liulanxiangzhu.service.impl;

import com.cake.liulanxiangzhu.mapper.UserShopMapper;
import com.cake.liulanxiangzhu.pojo.entity.UserShop;
import com.cake.liulanxiangzhu.pojo.vo.UserShopVO;
import com.cake.liulanxiangzhu.service.IWxLogin;
import com.cake.liulanxiangzhu.utils.LoginUtil;
import com.cake.liulanxiangzhu.web.ProductCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Service
public class WxLoginImpl implements IWxLogin {

    @Autowired
    UserShopMapper userShopMapper;

    @Autowired
    LoginUtil loginUtil;

    @Override
    public String queryToken(String code) {
        String openId = loginUtil.getOpenId(code);
        System.out.println("openId:"+openId);
        UserShopVO userShopVO = userShopMapper.queryUserId(openId);
        String token = "";
        if (userShopVO!=null){
            String userId = String.valueOf(userShopVO.getUserId());
            token = loginUtil.getToken(userId);
        }else {
            UserShop user = new UserShop();
            user.setOpenId(openId);
            user.setIsRegister(ProductCode.NO.getCode());
            user.setIsVip(ProductCode.NO.getCode());
            user.setVipLevel(ProductCode.NO.getCode());
            user.setCreatTime(new Date());
            user.setUpdateTime(new Date());
            userShopMapper.insert(user);
            UserShopVO queryUserId = userShopMapper.queryUserId(openId);
            String userId = String.valueOf(queryUserId.getUserId());
            token = loginUtil.getToken(userId);
        }
        System.out.println("token:"+token);
        return token;
    }

    @Override
    public String test(HttpServletRequest request) {
        String token = request.getHeader("Token");
        String id = loginUtil.parser(token).getId();

        return id;
    }


}
